package com.vip8.recorder.service.interceptor;


import com.vip8.recorder.service.model.LoginInfo;
import com.vip8.recorder.service.utils.JwtUtil;
import com.vip8.recorder.service.utils.UserThreadLocal;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;


public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String accessToken = request.getHeader("authToken");
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        if (accessToken == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new RuntimeException("登录态已失效，请重新登录");
        }
        LoginInfo loginInfo = JwtUtil.parseToken(accessToken);
        if (loginInfo == null) {
            throw new RuntimeException("登录态已失效，请重新登录");
        }
        UserThreadLocal.set(loginInfo);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserThreadLocal.clear();
    }
}
